package com.seek.inter;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.service.LoanService;
import com.seek.service.ReadService;
import com.seek.util.CommonUtil;

/**
 * 货款订单手工还款相关接口
 *
 */
public class LoanHandPayInter {
	private static Logger logger = LoggerFactory.getLogger(LoanHandPayInter.class);
	private LoanService loanService = (LoanService)SpringContextHolder.getBean("loanService");
	private ReadService readService = (ReadService)SpringContextHolder.getBean("readService");
	
	/**
	 * 手工收款>获取列表结果
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLoanListOfHandPay(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.end_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.end_time <= ?");
			params.add(rqz);
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.loan_status in (3,6)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		sb.append(" a.end_time endTime,a.req_date reqTime,(case when a.loan_status=6 then 1 else 0 end) isBad,")
		.append(" datediff(now(),a.end_time) delayDays,ifnull(a.late_fee - a.off_latefee,0) lateFee,a.overduer_id overduerId,")
		.append(" (select u.user_name from t_sys_user u where a.overduer_id=u.id) overduerName,a.last_overdue_time lastOverdueTime,b.id custId,")
		.append(" (select ifnull(sum(m.pay_money),0) from t_loan_repayment m where m.loan_id=a.id and m.type=2 and m.pay_type=3 and m.pay_status=1) handPayMoney")
		.append(" from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.loan_status in (3,6)");
		sb.append(where).append(" order by a.id asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 添加手工收款记录
	 * @return
	 * @throws Exception
	 */
	public ResultInfo addLoanHandPay(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		int money = CommonUtil.getIntValue(reqJson.get("money"));
		int latefee = CommonUtil.getIntValue(reqJson.get("latefee"));
		String payImg = reqJson.getString("payImg");
		String payor = reqJson.getString("payor");
		String _currnetUserId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1 || CommonUtil.isEmpty(payImg) || money<1 || latefee>money) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}

		try{
			loanService.addLoanHandPay(companyId, loanId, money, latefee,_currnetUserId, payor, payImg);
			result.setStatus(0);
			result.setMessage("成功");
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
	
	/**
	 * 查询贷款记录的手工收款记录清单
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLoanHandPayDetail(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}

		String sql = "select a.payor,a.pay_type payType,a.pay_money money,a.create_time createTime,(select u.user_name from t_sys_user u where u.id=a.recievor) recievor,a.reci_img payImg"
				    + " from t_loan_repayment a where a.loan_id=? and a.type=2 and a.pay_type=3 and a.pay_status=1 order by id desc";
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.findMapBySql(sql, new Object[]{loanId}));
		return result;
	}

	/**
	 * 设置货款订单手工还款已完成
	 * @return
	 * @throws Exception
	 */
	public ResultInfo handCloseLoan(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		String userId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}

		String sql = "update t_loan set loan_status=5,payback_date=now(),handclose_id=? where id=?";
		loanService.executeUpdate(sql, new Object[]{userId,loanId});
		loanService.refreshCachedUsedCredit(loanId);
	    
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 手工收款>获取手工关闭列表结果
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLoanHandCloseList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		int exclueClose = CommonUtil.getIntValue(reqJson.getString("exclueClose"));
		
		if(companyId == null || CommonUtil.isEmpty(custPhone)) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			where.append(" and b.phone_no=?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.end_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.end_time <= ?");
			params.add(rqz);
		}else{
			// where.append(" and a.end_time < now()");
		}
		if (exclueClose == 1){
			where.append(" and a.loan_status in (3,6)");
		}else{
			where.append(" and a.loan_status in (3,5,6)");
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		sb.append(" a.end_time endTime,a.req_date reqTime,(case when a.loan_status=6 then 1 else 0 end) isBad,")
		.append(" datediff(now(),a.end_time) delayDays,ifnull(a.late_fee - a.off_latefee,0) lateFee,")
		.append(" (select u.user_name from t_sys_user u where a.overduer_id=u.id) overduerName,a.last_overdue_time lastOverdueTime,")
		.append(" (select u.user_name from t_sys_user u where a.handclose_id=u.id) closerName,a.payback_date payBackDate,b.id custId,")
		.append(" (select ifnull(sum(m.pay_money),0) from t_loan_repayment m where m.loan_id=a.id and m.type=2 and m.pay_type=3 and m.pay_status=1) handPayMoney")
		.append(" from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=?");
		sb.append(where).append(" order by a.id asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
}
